package com.shiro.realm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author hjwStart
 * @time 2022-11-21 12:00
 * @version: 1.0
 */
@Slf4j
public class MyEncryptedRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // authenticationToken 就是调用 login 方法参入的参数
        String principals = authenticationToken.getPrincipal().toString();// 获取的就是username
        log.info("执行SQL");
        log.info("解析结果集");
        String credentials = "79ae1231b5934424660a8e5f2aa91393"; // 从数据库中查询出来的暗文密码
        SimpleAuthenticationInfo authenticationInfo = null;
        if ("admin".equals(principals) || "hjw".equals(principals)){
            /*
                参数说明：
                    1.principals：用户名
                    2.credentials：密码
                    3.credentialsSalt：盐值
                    4.当前Realm的名字，调用getName()方法就行，返回全类名
             */
            authenticationInfo = new SimpleAuthenticationInfo(principals,credentials, ByteSource.Util.bytes("salt"),this.getName());
        }else {
            log.error("用户不存在");
        }
        return authenticationInfo;
    }
}
